package com.newly.common.core.service.core.impl;

import cn.hutool.core.util.ObjectUtil;
import com.newly.common.base.entity.sys.api.ApiDto;
import com.newly.common.core.service.core.api.ICoreService;
import com.newly.transfer.redis.RedisTransfer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: newly-parent
 * @remark:
 * @author: guan
 * @create: 2022-01-09 18:26
 */
@Service
@Slf4j
public class CoreService extends AbstractCoreService implements ICoreService {

    @Autowired
    private RedisTransfer redisTransfer;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Override
    public boolean setCacheApis() {
        redisTransfer.clearApis(serverProperty.serverName);

        Set<String> classNames = this.scanApiPackege();
        if (ObjectUtil.isEmpty(classNames)) return false;

        // 封装ApiDto对象
        Set<ApiDto> allApiDto = new HashSet<>(128);
        for (String className : classNames) {
            try {
                List<ApiDto> apiDtos = this.packageApiDtos(className);
                if (ObjectUtil.isEmpty(apiDtos)) continue;
                allApiDto.addAll(apiDtos);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 缓存api接口至redis中
        String serverName = serverProperty.getServerName();
        for (ApiDto apiDto : allApiDto) {
            redisTransfer.addApis(serverName, apiDto);
        }

        return true;
    }

    @Override
    public List<ApiDto> getCacheApis() {
        List<String> services = discoveryClient.getServices();
        List<ApiDto> allApiDto = new ArrayList<>();
        for (String service : services) {
            List<ApiDto> apis = redisTransfer.getApis(service);
            if (ObjectUtil.isEmpty(apis)) continue;
            allApiDto.addAll(apis);
        }
        return allApiDto.stream().distinct().collect(Collectors.toList());
    }

    @Override
    public List<ApiDto> getCacheApis(String serverName) {
        return redisTransfer.getApis(serverName);
    }
}
